// -------------------------------------------------------------------------------------
// _askop
// Establishes remote-object connection with main app to ask operator questions
// -------------------------------------------------------------------------------------
// Permission is granted to freely redistribute this source code, and to use fragments
// of this code in your own applications if you find them to be useful.  This class/module,
// along with the source code, come with no warranty of any kind, and the user assumes
// all responsibility for its use.
// -------------------------------------------------------------------------------------

#import <mach/mach.h>
#import <stdio.h>
#import <strings.h>
#import <libc.h>
#import <remote/NXConnection.h>
#import <appkit/Application.h>
#import "AskOperator.h"

@interface _RmtMethods : Object
- (const char*)getResponseForMessage:(askOperator_t*)ao;
@end

void main (int argc, char *argv[])
{
	int				i;
	BOOL			doAskOp = YES;
	askOperator_t	askop;
	id				ss;
	char			*host, *server;
	
	/* check proper arg count */
	if (argc < 3) {
		int a;
		
		/* make sure we're starting on a new line */
		fprintf(stderr, "\n");
		
		/* print command as specified */
		fprintf(stderr, "%s", argv[0]);
		for (a = 1; a < argc; a++) fprintf(stderr, " \"%s\"", argv[a]);
		fprintf(stderr, "\n");
		
		/* print usage */
		fprintf(stderr,
			"usage: %s [-hhost] title msg [b1 [b2 [b3 [b4]]]]\n", argv[0]);
			
		/* exit */
		exit(1);
		
	}

	/* defaults */
	memset(&askop, 0, sizeof(askop));
	askop.type = 0;

	/* parse: askop -hmandi "Title" "Message" "B1" "B2" "B3" "B4" */
	for (i = 1; i < argc; i++) {
		if (*argv[i] != '-') break;
		switch (argv[i][1]) {
			case 'n':	// don't ask-op
				doAskOp = NO;
				break;
			case 'h':	// remote host name
				strcpy(askop.host, &argv[i][2]);
				break;
		}
	}
	if (i < argc) strcpy(askop.title    , argv[i++]);
	if (i < argc) strcpy(askop.message  , argv[i++]);
	if (i < argc) strcpy(askop.button[0], argv[i++]); else askop.type = 1;
	if (i < argc) strcpy(askop.button[1], argv[i++]);
	if (i < argc) strcpy(askop.button[2], argv[i++]);
	if (i < argc) strcpy(askop.button[3], argv[i++]);

	/* establish connection */
	if (!(server = getenv("SERVERNAME")) || !*server) server = ASK_SERVER;
	host = (*askop.host? askop.host : getenv("SERVERHOST"));
	if (host && !*host) host = (char*)nil;
	[NXConnection setDefaultTimeout:-1];
	if (!(ss = [NXConnection connectToName:server onHost:host])) {
		fprintf(stderr, "%s: Cannot connect to server '%s' on host '%s'\n", argv[0],
				server, (host?host:"<local>"));
		exit(1);
	}

	/* print results */
	if (doAskOp) printf("%s\n", [ss getResponseForMessage:&askop]);
	
}
